package com.service.dealer;

import com.common.ErrorCodeEnum;
import com.common.emums.DataStatus;
import com.common.exception.BusinessException;
import com.common.utils.MD5;
import com.common.utils.StringUtils;
import com.core.springSecurity.common.SecurityUtils;

import com.dao.primary.dealer.DealerInfoMapper;
import com.dao.primary.user.UserInfoMapper;
import com.model.domain.dealer.GetDealerInfoDO;
import com.model.pojo.dealer.DealerInfo;
import com.model.pojo.user.UserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



/**
 * @Author: zql
 * @Description: 【请填写功能名称】服务
 * @Data: 2023-08-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DealerInfoService {
    private final DealerInfoMapper dealerInfoMapper;
    private final UserInfoMapper userInfoMapper;

    public List<DealerInfo> getPageList(GetDealerInfoDO getDealerInfoDO){
        PageHelper.clearPage();
        PageHelper.startPage(getDealerInfoDO.getPage(),getDealerInfoDO.getPageSize(),getDealerInfoDO.getSortRow()+getDealerInfoDO.getSortOrder());
        return dealerInfoMapper.selectList(getDealerInfoDO);
    }

    public DealerInfo findById(Long id){
        return dealerInfoMapper.selectByPrimaryKey(id);
    }
    @Transactional
    public int save(DealerInfo info,String password){
        UserInfo userInfo = userInfoMapper.selectByCellphone(info.getDealerPhone());
        if(userInfo!=null){
            if(userInfo.getUserType()!=2){
                return 0;
            }
            info.setDealerUserId(userInfo.getId());
        }else{
            userInfo = new UserInfo();
            userInfo.setCellphone(info.getDealerPhone());
            userInfo.setPassword(MD5.encode(password, "utf-8"));
            userInfo.setName(info.getDealerName());
            userInfo.setUserType(2);
            userInfo.setRegisterTime(new Date());
            userInfoMapper.insertSelective(userInfo);
        }
        if(userInfo!=null && userInfo.getId()>0){
            info.setDealerUserId(userInfo.getId());
            info.setCreateTime(new Date());
            return dealerInfoMapper.insertSelective(info);
        }
        return 0 ;
    }

    @Transactional
    public int update(DealerInfo info,String password){
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(info.getDealerUserId());
        if(userInfo!=null){
            userInfo.setPassword(MD5.encode(password, "utf-8"));
            userInfoMapper.updateByPrimaryKeySelective(userInfo);
        }
        return dealerInfoMapper.updateByPrimaryKeySelective(info);
    }

    public int delete(DealerInfo info){
        info.setIsDelete(-1);
        return dealerInfoMapper.updateByPrimaryKeySelective(info);
    }
}
